package com.yanfan.modbus.frame;


import com.yanfan.modbus.code.FunctionCode;
import com.yanfan.modbus.exception.ModbusTransportException;
import com.yanfan.modbus.frame.abs.ModbusResponse;
import io.netty.buffer.ByteBuf;


public class ReportSlaveIdResponse extends ModbusResponse {
    private byte[] data;

    public ReportSlaveIdResponse(int slaveId) throws ModbusTransportException {
        super(slaveId);
    }

    public ReportSlaveIdResponse(int slaveId, byte[] data) throws ModbusTransportException {
        super(slaveId);
        this.data = data;
    }


    @Override
    public byte getFunctionCode() {
        return FunctionCode.REPORT_SLAVE_ID;
    }

    @Override
    protected void readResponse(ByteBuf buf) {
        int numberOfBytes = buf.readUnsignedByte();
        if (buf.readableBytes() < numberOfBytes) {
            throw new ArrayIndexOutOfBoundsException();
        }

        data = new byte[numberOfBytes];
        buf.readBytes(data);
    }


    @Override
    protected void writeResponse(ByteBuf queue) {
        queue.writeByte(data.length);
        queue.writeBytes(data);
    }


    public byte[] getData() {
        return data;
    }
}
